from sqlalchemy import *
from core.db import *
from core import *
import re

class qTranslation(object):
	def __init__(self,qAye,translation,type):
		self.aye_id = qAye.id
		self.fa = translation
		self.tr_type = type
	def __repr__(self):
		pass


tr_table = Table('tr_table',metadata,
		Column('aye_id',Integer,ForeignKey("aye_table.id"),primary_key=True),
		Column('tr_type',Integer),
		Column('fa',String))


tr_mapper = mapper(qTranslation,tr_table,order_by=tr_table.c.aye_id,properties={'aye':relation(qpath.qAye,backref=backref('translation',uselist=False))})
tr_query = session.query(qTranslation)



def isSupportQuery(query,domain=""):
	r = re.compile("^\s*translation{([^}]*)}\s*$").search(query)
	return (r != None)

def start_filter(sureQ,ayeQ,query):
	log.logger.debug('servers.translation.start_filter(%s,%s,%s)' % (sureQ,ayeQ,query))
	r = re.compile("^\s*translation{([^}]*)}\s*$").search(query)
	q = r.group(1)
	result = []
	wa = [tr.aye for tr in tr_query.select(qTranslation.c.fa.like("%"+q+"%"))]
	for a in wa:
		if qpath.isAyeInQPath(a,sureQ,ayeQ):
			result.append(a)
	log.logger.debug('	result:%d' % len(result))		
	return result		


def filter(query,domain):
	"""
	will filter queries with format
	"translation{REGULAR_EXPRESSION}" on domain and return results
	"""
	r = re.compile("^\s*translation{([^}]*)}\s*$").search(query)
	query = r.group(1)
	result = []
	d1 = []
	for d in domain:
		if isinstance(d,qpath.qAye) :
			d1.append(d)
		if isinstance(d,qpath.qSure) :
			d1 = d1 + d.ayat
		if isinstance(d,qpath.qWord) :
			d1.append(d.aye)
	reg = re.compile(query)		
	for x in d1:
		regr = reg.search(x.translation.fa)
		if regr != None:
			result.append(x)
	return result

log.logger.info("adding translation module to qpath server")
qpath.server_isSupports.append(isSupportQuery)
qpath.server_filter.append(filter)

qpath.server_isStartSupports.append(isSupportQuery)
qpath.server_start_filter.append(start_filter)

if __name__ == "__main__":
	pass
